package com.reggie.controller;

import com.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/common")
public class commonController {
    @Value("${basePath}")
    private String basePath;

    /**
     * @param file
     * @return com.reggie.common.R<java.lang.String>
     * @description: 文件转存到本地
     * @author 86187
     * @date: 2022/11/18 14:08
     */

    @PostMapping("/upload")
    public R<String> uploadFile(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        System.out.println(suffix);
        String fileName = UUID.randomUUID().toString() + suffix;
        File fileInfo = new File(basePath);
        if (!fileInfo.exists()) {
            System.out.println("test......");
            fileInfo.mkdirs();
        }
        try {
            //将临时文件转存到指定位置
            file.transferTo(new File(basePath + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(fileName);

    }

    /**
     * @param name
     * @param response
     * @return void
     * @description: 文件回显到页面, 使用io流实现
     * @author 86187
     * @date: 2022/11/18 14:08
     */

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        response.setContentType("image/jpeg");
        try {
            inputStream = new FileInputStream(basePath + name);
            outputStream = response.getOutputStream();
            int len = 0;
            byte[] b = new byte[1024];
            while ((len = inputStream.read(b)) != -1) {
                outputStream.write(b, 0, len);
                //刷新
                outputStream.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}